package com.spring.boot.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring.boot.dao.UserMapper;
import com.spring.boot.entity.User;
import com.spring.boot.service.UserService;
import com.spring.boot.utils.MD5Util;
import com.spring.boot.utils.ServiceException;
import com.spring.boot.vo.ChangePasswordVO;
import com.spring.boot.vo.QueryRequest;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: Daniel ZTQ
 * @Date: 2021/01/01 22:59
 * @Description: 用户信息业务逻辑层 接口实现
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册实现接口(普通用户/管理员)
     */
    @Override
    public Map<String, Object> addUser(User user) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        try {
            //获取用户姓名
            String userName = user.getUserName();
            //获取用户密码
            String password1 = user.getPassword();
            //获取用户性别
            Integer gender = user.getGender();
            //获取用户身份证号
            String idCard1 = user.getIdCard();
            //获取用户手机号
            String mobile = user.getMobile();
            //获取用户权限
            String role = user.getRole();
            //获取用户地址
            String address = user.getAddress();
            //如果用户姓名为空
            if (userName == null || userName.equals("")) {
                //日志打印
                log.info("用户姓名不能为空！");
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", "用户姓名不能为空！");
                //设置status值
                result.put("status", false);
                //返回result
                return result;
            }
            //如果登录密码为空
            if (password1 == null || password1.equals("")) {
                //日志打印
                log.info("登录密码不能为空！");
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", "登录密码不能为空！");
                //设置status值
                result.put("status", false);
                //返回result
                return result;
            }
            //如果性别为空
            if (gender == null) {
                //日志打印
                log.info("用户性别不能为空！");
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", "用户性别不能为空！");
                //设置status值
                result.put("status", false);
                //返回result
                return result;
            }
            //如果身份证号为空
            if (idCard1 == null || idCard1.equals("")) {
                //日志打印
                log.info("用户身份证号不能为空！");
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", "用户身份证号不能为空！");
                //设置status值
                result.put("status", false);
                //返回result
                return result;
            }
            //如果手机号为空
            if (mobile == null || mobile.equals("")) {
                //日志打印
                log.info("用户手机号不能为空！");
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", "用户手机号不能为空！");
                //设置status值
                result.put("status", false);
                //返回result
                return result;
            }
            //如果角色权限为空
            if (role == null || role.equals("")) {
                //日志打印
                log.info("用户角色不能为空！");
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", "用户角色不能为空！");
                //设置status值
                result.put("status", false);
                //返回result
                return result;
            }
            //如果用户地址为空
            if (address == null || address.equals("")) {
                //日志打印
                log.info("用户地址不能为空！");
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", "用户地址不能为空！");
                //设置status值
                result.put("status", false);
                //返回result
                return result;
            }
            //获取用户身份证号
            String idCard = user.getIdCard();
            //调用sql，根据身份证号查询User表中是否存在该用户
            List<User> userByIdCare = userMapper.getUserByIdCare(idCard);
            //如果表中存在该数据
            if (userByIdCare.size() > 0) {
                //日志打印
                log.info("用户已存在，请直接登录！");
                //设置msg值
                result.put("msg", "用户已存在，请直接登录！");
                //设置状态码
                result.put("code", 300);
                //设置status值
                result.put("status", false);
            } else {
                //获取当前时间为创建时间
                user.setCreatedTime(new Date());
                //获取更新时间为创建时间
                user.setUpdateTime(new Date());
                //获取密码
                String password = user.getPassword();
                //将密码进行md5加密
                user.setPassword(MD5Util.encrypt(password));
                //调用userMapper层的insert的sql，新增用户
                userMapper.insert(user);
                //日志打印
                log.info("注册成功！");
                //设置msg值
                result.put("msg", "注册成功！");
                //设置状态码
                result.put("code", 200);
                //设置status值
                result.put("status", true);
            }
        } catch (Exception e) {
            //日志打印"用户注册失败"
            log.error("用户注册调用接口失败", e);
            //设置msg值
            result.put("msg", "用户注册调用接口失败！");
            //设置status值
            result.put("status", false);
            //设置状态码
            result.put("code", 500);
            //抛出异常
            throw new ServiceException("用户注册失败");
        }
        //返回数据信息
        return result;
    }

    /**
     * 用户登录实现接口（普通用户/管理员/财务人员）
     */
    @Override
    public Map<String, Object> longin(String idCard, String password) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        try {
            //调用sql，根据身份证号查询User表中是否存在该用户
            List<User> userByIdCare = userMapper.getUserByIdCare(idCard);
            //如果表中存在该用户
            if (userByIdCare.size() > 0) {
                //获取表中该用户的密码
                String reallyPassword = userByIdCare.get(0).getPassword();
                //将用户填写的登录的密码进行加密
                String encryptPassword = MD5Util.encrypt(password);
                //判断填写的密码是否等于表中的密码
                boolean flag = encryptPassword.equals(reallyPassword);
                //如果为真，则说明密码正确，否则密码输入错误
                if (flag) {
                    //获取用户角色
                    String role = userByIdCare.get(0).getRole();
                    //获取用户id
                    String uid = userByIdCare.get(0).getUid().toString();
                    //获取用户信息
                    User userByUid = userMapper.getUserByUid(uid);
                    //日志打印
                    log.info("登陆成功！");
                    //设置msg值
                    result.put("msg", "登陆成功！");
                    //设置用户id
                    result.put("data", userByUid);
                    //设置状态码
                    result.put("code", 200);
                    //设置status值
                    result.put("status", true);
                } else {
                    //日志打印
                    log.info("密码输入错误，请重新输入！");
                    //设置msg值
                    result.put("msg", "密码输入错误，请重新输入！");
                    //设置状态码
                    result.put("code", 300);
                    //设置status值
                    result.put("status", false);
                }
            } else {
                //日志打印"账号不存在，请重新输入"
                log.error("账号不存在，请重新输入");
                //设置msg值
                result.put("msg", "账号不存在，请重新输入！");
                //设置status值
                result.put("status", false);
                //设置状态码
                result.put("code", 300);
            }
        } catch (Exception e) {
            //日志打印"登录接口调用失败"
            log.error("登录接口调用失败", e);
            //设置msg值
            result.put("msg", "登录接口调用失败！");
            //设置status值
            result.put("status", false);
            //设置状态码
            result.put("code", 500);
            //抛出异常
            throw new ServiceException("登录接口调用失败");
        }
        //返回数据信息
        return result;
    }

    /**
     * 批量删除用户实现接口（管理员）
     */
    @Override
    public Map<String, Object> deleteBatchIdsUser(String uid) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        try {
            //以逗号分隔
            String[] split = uid.split(",");
            //创建list集合
            List<String> idList = new ArrayList<>();
            //for循环遍历，以逗号分隔 要删除的用户
            for (String str : split) {
                //将要删除的用户信息 放入list集合里面
                idList.add(str);
            }
            //调用userMapper层的deleteBatchIds的sql，批量删除用户
            userMapper.deleteBatchIds(idList);
            //日志打印
            log.info("删除用户信息成功");
            //设置状态码
            result.put("code", 200);
            //设置msg值
            result.put("msg", "删除用户信息成功！");
            //设置status值
            result.put("status", true);
        } catch (Exception e) {
            //日志打印“用户删除失败”
            log.error("用户删除失败", e);
            //设置状态码
            result.put("code", 500);
            //设置msg值
            result.put("msg", "删除用户信息失败！");
            //设置status值
            result.put("status", false);
            //抛出异常
            throw new ServiceException("用户删除失败");
        }
        //返回数据信息
        return result;
    }

    /**
     * 修改用户实现接口（普通用户/管理员/财务人员 （注：普通用户和财务人员仅可修改自己的用户信息））
     */
    @Override
    public Map<String, Object> updateUser(User user) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        try {
            //获取用户身份证号
            String idCard = user.getIdCard();
            //调用sql，根据身份证号查询User表中是否存在该用户
            List<User> userByIdCare = userMapper.getUserByIdCare(idCard);
            //如果表中存在该数据
            if (userByIdCare.size() > 0) {
                //日志打印
                log.info("用户已存在，请直接登录！");
                //设置msg值
                result.put("msg", "用户已存在，请直接登录！");
                //设置状态码
                result.put("code", 300);
                //设置status值
                result.put("status", false);
                return result;
            }
            //设置更新时间
            user.setUpdateTime(new Date());
            //调用userMapper层的updateById的sql修改用户信息
            userMapper.updateById(user);
            //日志打印
            log.info("修改信息成功");
            //设置状态码
            result.put("code", 200);
            //设置msg值
            result.put("msg", "修改成功！");
            //设置status值
            result.put("status", true);
        } catch (Exception e) {
            //日志打印“调用用户修改信息接口失败”
            log.error("调用用户修改信息接口失败", e);
            //设置状态码
            result.put("code", 500);
            //设置msg值
            result.put("msg", "调用用户修改信息接口失败！");
            //设置status值
            result.put("status", false);
            //抛出异常
            throw new ServiceException("调用用户修改信息接口失败");
        }
        //返回结果
        return result;
    }

    /**
     * 查询用户信息实现接口（管理员）
     */
    @Override
    public Map<String, Object> findUserList(QueryRequest request, User user) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        try {
            //创建一个user对象
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //如果获取到的用户姓名不为空
            if (StringUtils.isNotEmpty(user.getUserName())) {
                //则根据姓名进行模糊查询
                lambdaQueryWrapper.like(User::getUserName, user.getUserName());
            }
            //如果获取到的用户身份证号不为空
            if (StringUtils.isNotEmpty(user.getIdCard())) {
                //则根据身份证号进行查询（非模糊查询）
                lambdaQueryWrapper.eq(User::getIdCard, user.getIdCard());
            }
            //如果获取到的手机号不为空
            if (StringUtils.isNotEmpty(user.getMobile())) {
                //则根据手机号进行查询（非模糊查询）
                lambdaQueryWrapper.eq(User::getMobile, user.getMobile());
            }
            //根据用户id进行正序排序
            lambdaQueryWrapper.orderByAsc(User::getUid);
            //创建分页对象
            Page<User> page = new Page<>(request.getPageNum(), request.getPageSize());
            //进行分页处理
            IPage<User> page1 = this.page(page, lambdaQueryWrapper);
            //设置状态码
            result.put("code", 200);
            //设置data值
            result.put("data", page1);
            //设置msg值
            result.put("msg", "查询用户信息成功！");
            //设置status值
            result.put("status", true);
        } catch (Exception e) {
            //打印日志
            log.error("查询用户信息失败:", e);
            //设置状态码
            result.put("code", 500);
            //设置msg值
            result.put("msg", "调用查询用户信息接口失败！");
            //设置status值
            result.put("status", false);
            throw new ServiceException("调用查询用户信息接口失败！");
        }
        return result;
    }

    /**
     * @param uid 用户id
     * @return map
     * @description: 查看个人信息（管理员/财务/普通用户）
     */
    @Override
    public Map<String, Object> getPersonalInformationByUid(String uid) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        try {
            //根据uid查询自己的用户信息
            User userByUid = userMapper.getUserByUid(uid);
            //设置状态码
            result.put("code", 200);
            //设置data值
            result.put("data", userByUid);
            //设置msg值
            result.put("msg", "查询个人信息成功！");
            //设置status值
            result.put("status", true);
        } catch (Exception e) {
            //打印日志
            log.error("查询个人信息失败:", e);
            //设置状态码
            result.put("code", 500);
            //设置msg值
            result.put("msg", "调用查询个人信息接口失败！");
            //设置status值
            result.put("status", false);
            throw new ServiceException("调用查询个人信息接口失败！");
        }
        return result;
    }

    /**
     * 修改密码
     */
    @Override
    public Map<String, Object> changePassword(ChangePasswordVO changePasswordVO) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        try {
            //调用验证方法，判断封装的修改密码是否不为空
            String s = changePasswordVO.verifyData();
            //如果为空，说明参数正确
            if (StringUtils.isBlank(s)) {
                //根据uid，获取用户信息
                User userByUid = userMapper.getUserByUid(changePasswordVO.getUid());
                //如果用户信息不为空
                if (userByUid != null) {
                    //将前端输入的原密码进行加密
                    String encrypt = MD5Util.encrypt(changePasswordVO.getOldPassword());
                    //获取库里存储的原密码
                    String password = userByUid.getPassword();
                    //如果输入的原密码正确
                    if (encrypt.equals(password)) {
                        //调用修改密码方法
                        int i = userMapper.updatePassword(changePasswordVO.getUid(), MD5Util.encrypt(changePasswordVO.getNewPassword()));
                        //如果修改成功
                        if (i > 0) {
                            //设置状态码
                            result.put("code", 200);
                            //设置data值
                            result.put("data", "修改密码成功");
                            //设置msg值
                            result.put("msg", "修改密码成功！");
                            //设置status值
                            result.put("status", true);
                        } else {
                            //如果修改失败
                            //设置状态码
                            result.put("code", 300);
                            //设置data值
                            result.put("data", "修改密码失败");
                            //设置msg值
                            result.put("msg", "修改密码失败！");
                            //设置status值
                            result.put("status", false);
                        }
                    } else {
                        //如果原密码输入错误
                        //设置状态码
                        result.put("code", 300);
                        //设置data值
                        result.put("data", "原密码输入错误，请重新输入");
                        //设置msg值
                        result.put("msg", "原密码输入错误，请重新输入！");
                        //设置status值
                        result.put("status", false);
                    }
                } else {
                    //如果用户不存在
                    //设置状态码
                    result.put("code", 300);
                    //设置data值
                    result.put("data", "该用户不存在");
                    //设置msg值
                    result.put("msg", "该用户不存在！");
                    //设置status值
                    result.put("status", false);
                }
            } else {
                //如果用户id或原密码或新密码为空
                log.info(s);
                //设置状态码
                result.put("code", 300);
                //设置msg值
                result.put("msg", s);
                //设置status值
                result.put("status", false);
            }
        } catch (Exception e) {
            //打印日志
            log.error("调用修改密码接口失败:", e);
            //设置状态码
            result.put("code", 500);
            //设置msg值
            result.put("msg", "调用修改密码接口失败！");
            //设置status值
            result.put("status", false);
            throw new ServiceException("调用修改密码接口失败！");
        }
        return result;
    }

    /**
     * 查询菜单
     */
    @Override
    public Map<String, Object> findMenu(String role) {
        //定义map对象
        Map<String, Object> result = new HashMap<>();
        //定义菜单对象
        String menu = "";
        try {
            //管理员菜单
            if ("0".equals(role)) {
                menu = "[\n" +
                        "  {\n" +
                        "    \"title\": \"主页\",\n" +
                        "    \"icon\": \"layui-icon-home\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"控制台\",\n" +
                        "        \"jump\": \"/\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"title\": \"用户管理\",\n" +
                        "    \"name\": \"user\",\n" +
                        "    \"icon\": \"layui-icon-username\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"用户管理\",\n" +
                        "        \"jump\": \"user/user/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"title\": \"险种管理\",\n" +
                        "    \"name\": \"insuranse\",\n" +
                        "    \"icon\": \"layui-icon-vercode\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"险种管理\",\n" +
                        "        \"jump\": \"insurance/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"title\": \"合同管理\",\n" +
                        "    \"name\": \"contract\",\n" +
                        "    \"icon\": \"layui-icon-file\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"合同\",\n" +
                        "        \"jump\": \"contract/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"order\",\n" +
                        "    \"title\": \"保单管理\",\n" +
                        "    \"icon\": \"layui-icon-rmb\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"保单\",\n" +
                        "        \"jump\": \"order/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"insured\",\n" +
                        "    \"title\": \"被保险人\",\n" +
                        "    \"icon\": \"layui-icon-user\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"被保险人管理\",\n" +
                        "        \"jump\": \"user/manage/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"flow\",\n" +
                        "    \"title\": \"日结账\",\n" +
                        "    \"icon\": \"layui-icon-list\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"财务流水\",\n" +
                        "        \"jump\": \"flow/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"count\",\n" +
                        "    \"title\": \"统计\",\n" +
                        "    \"icon\": \"layui-icon-list\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"交易量\",\n" +
                        "        \"jump\": \"count/count\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"query\",\n" +
                        "    \"title\": \"综合查询\",\n" +
                        "    \"icon\": \"layui-icon-search\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"综合查询\",\n" +
                        "        \"jump\": \"query/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  }\n" +
                        "]";
            } else if ("1".equals(role)) {
                //财务人员菜单
                menu = "[\n" +
                        "  {\n" +
                        "    \"title\": \"主页\",\n" +
                        "    \"icon\": \"layui-icon-home\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"控制台\",\n" +
                        "        \"jump\": \"/\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"title\": \"合同管理\",\n" +
                        "    \"name\": \"contract\",\n" +
                        "    \"icon\": \"layui-icon-file\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"合同\",\n" +
                        "        \"jump\": \"contract/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"order\",\n" +
                        "    \"title\": \"保单管理\",\n" +
                        "    \"icon\": \"layui-icon-rmb\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"保单\",\n" +
                        "        \"jump\": \"order/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"flow\",\n" +
                        "    \"title\": \"日结账\",\n" +
                        "    \"icon\": \"layui-icon-list\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"财务流水\",\n" +
                        "        \"jump\": \"flow/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "]";
            } else {
                //普通用户菜单
                menu = "[\n" +
                        "  {\n" +
                        "    \"title\": \"主页\",\n" +
                        "    \"icon\": \"layui-icon-home\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"控制台\",\n" +
                        "        \"jump\": \"/\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"title\": \"险种管理\",\n" +
                        "    \"name\": \"insuranse\",\n" +
                        "    \"icon\": \"layui-icon-vercode\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"险种管理\",\n" +
                        "        \"jump\": \"insurance/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"title\": \"合同管理\",\n" +
                        "    \"name\": \"contract\",\n" +
                        "    \"icon\": \"layui-icon-file\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"合同\",\n" +
                        "        \"jump\": \"contract/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"order\",\n" +
                        "    \"title\": \"保单管理\",\n" +
                        "    \"icon\": \"layui-icon-rmb\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"保单\",\n" +
                        "        \"jump\": \"order/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  {\n" +
                        "    \"name\": \"insured\",\n" +
                        "    \"title\": \"被保险人\",\n" +
                        "    \"icon\": \"layui-icon-user\",\n" +
                        "    \"list\": [\n" +
                        "      {\n" +
                        "        \"title\": \"被保险人管理\",\n" +
                        "        \"jump\": \"user/manage/list\"\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  }\n" +
                        "]";
            }
            JSONArray array = JSONUtil.parseArray(menu);
            result.put("data", array);

            log.info("查询菜单成功！");
            result.put("code", 200);
            result.put("msg", "查询菜单成功！");
            result.put("status", true);
        } catch (Exception e) {
            //打印日志
            log.error("查询菜单失败:", e);
            //设置状态码
            result.put("code", 500);
            //设置msg值
            result.put("msg", "查询菜单失败！");
            //设置status值
            result.put("status", false);
            throw new ServiceException("查询菜单失败！");
        }
        return result;
    }

}
